package com.jinzhi.jzweb.service.impl.moduleConfig;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.domain.TrackDrawDO;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.pojo.TrainingAgencyPageVo;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.service.moduleConfig.TrackDrawService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.TrackDrawDao;
import com.jinzhi.common.base.CoreServiceImpl;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 赛道抽签表（存储抽签信息）
 * </pre>
 * <small> 2024-02-28 09:32:18 | lance</small>
 */
@Service
public class TrackDrawServiceImpl extends CoreServiceImpl<TrackDrawDao, TrackDrawDO> implements TrackDrawService {

    @Autowired
    private StuSignUpComService stuSignUpComService;

    @Autowired
    private CareStuSignUpComRealityService careStuSignUpComRealityService;


    //存储处理完后的学校信息
    private List<StuSignUpComDO> distinctStuSignUpComDOS;

    /**
     * 领队抽签 需要分页
     *
     * 对每个院校进行检录号抽签
     *
     *
     * @param trackDrawDTO
     * @return
     */
    @Override
    public Result<Page<TrackDrawDO>> trackDrawList(TrackDrawDO trackDrawDTO) {
        //查询总条数
        LinkedList<String> numList = new LinkedList<>();
        int i = this.selectCount(new EntityWrapper<TrackDrawDO>());
        for (int j = 1; j <= i; j++) {
            numList.add(String.valueOf(j));
        }

        //把需要固定的检录号先从检录号列表中移除
        List<TrackDrawDO> trackDrawDOS1 = this.selectList(new EntityWrapper<TrackDrawDO>().isNotNull("place_num"));
        if(null!=trackDrawDOS1 && !trackDrawDOS1.isEmpty()){
            for (TrackDrawDO trackDrawDO : trackDrawDOS1) {
                numList.remove(trackDrawDO.getPlaceNum());
            }
        }

        //查询已经抽签的检录号 并且删除已经抽完的检录号
        List<TrackDrawDO> trackDrawDOS = this.selectList(new EntityWrapper<TrackDrawDO>().isNotNull("record_number"));
        if(null!=trackDrawDOS && !trackDrawDOS.isEmpty()){
            for (TrackDrawDO trackDrawDO : trackDrawDOS) {
                numList.remove(trackDrawDO.getRecordNumber());
            }
        }

        //查询当前页参赛选手信息 这里需要重复抽签 则当前页的检录号可以重复抽
        Page<TrackDrawDO> page = new Page<TrackDrawDO>(trackDrawDTO.getPageNumber(),trackDrawDTO.getPageSize());
        Wrapper<TrackDrawDO> entityWrapper =new EntityWrapper<TrackDrawDO>();
        entityWrapper.orderBy(true,"sort");
        Page<TrackDrawDO> pages = this.selectPage(page, entityWrapper);
        List<TrackDrawDO> records = pages.getRecords();

        //当前页的检录号重新放到抽签的列表中
        if(null!=records.get(0).getRecordNumber()){
            for (TrackDrawDO record : records) {
                numList.add(String.valueOf(record.getRecordNumber()));
            }

        }
        //打乱一下存放检录号的列表
        Random random = new Random();
        Collections.shuffle(numList,random);
        for (TrackDrawDO record : records) {
            if(null!=record.getPlaceNum()){
                record.setRecordNumber(record.getPlaceNum());
                numList.remove(record.getPlaceNum());
            }else{
                record.setRecordNumber(numList.getFirst());
                numList.removeFirst();
            }
            //检录号同步到真实的选手管理表
            CareStuSignUpComRealityDO careStuSignUpComRealityDO = new CareStuSignUpComRealityDO();
            careStuSignUpComRealityDO.setRecordNumber(Integer.valueOf(record.getRecordNumber()));
            careStuSignUpComRealityService.update(careStuSignUpComRealityDO,new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name",record.getUnitName()));
            //同步到虚拟表
            StuSignUpComDO stuSignUpComDO = new StuSignUpComDO();
            stuSignUpComDO.setRecordNumber(record.getRecordNumber());
            stuSignUpComService.update(stuSignUpComDO,new EntityWrapper<StuSignUpComDO>().eq("unit_name",record.getUnitName()));

        }
        this.updateBatchById(records);
        records.get(0).setHasDraw(true);
        records.get(0).setTotal(pages.getTotal());
        pages.setRecords(records);
        return Result.ok(pages);
    }

    /**
     * 查询上一次的抽签结果
     * @param trackDrawDTO
     * @return
     */
    @Override
    public Page<TrackDrawDO> trackList(TrackDrawDO trackDrawDTO) {
        Page<TrackDrawDO> page = new Page<TrackDrawDO>(trackDrawDTO.getPageNumber(), trackDrawDTO.getPageSize());
        //存储抽签你信息
        boolean hasDraw = true;//默认为true.不存在上次抽签结果时改为false

        //查询上一次的抽签结果
        Wrapper<TrackDrawDO> wrapper = new EntityWrapper<>();
        wrapper.orderBy(true,"sort");
        Page<TrackDrawDO> trackDrawDOPage = this.selectPage(page, wrapper);
        List<TrackDrawDO> trackDrawDOS = trackDrawDOPage.getRecords();

        //如果没有抽签上一次抽签结果那就默认初始化
        if(trackDrawDOS==null || trackDrawDOS.size()==0){
            hasDraw = false;
            Wrapper<CareStuSignUpComRealityDO> entityWrapper =new EntityWrapper<>();
            List<CareStuSignUpComRealityDO> stuSignUpComDOS = careStuSignUpComRealityService.selectList(entityWrapper);
            List<CareStuSignUpComRealityDO> distinctStuSignUpComDOS = stuSignUpComDOS.stream()
                    .collect(Collectors.toMap(CareStuSignUpComRealityDO::getUnitName, s -> s, (s1, s2) -> {
                        // 如果placeNum不为空，优先保留具有非空placeNum的对象
                        if (s1.getPlaceNum() != null && !s1.getPlaceNum().isEmpty()) {
                            return s1;
                        } else {
                            return s2;
                        }
                    }))
                    .values()
                    .stream()
                    .sorted(Comparator.comparing(CareStuSignUpComRealityDO::getPlaceNum, Comparator.nullsLast(Comparator.naturalOrder())))
                    .collect(Collectors.toList());
            int i=0;
            for (CareStuSignUpComRealityDO stuSignUpComDO : distinctStuSignUpComDOS) {
                TrackDrawDO trackDrawDO = new TrackDrawDO();
                BeanUtils.copyProperties(stuSignUpComDO,trackDrawDO);
                trackDrawDO.setSort(i+=1);
                trackDrawDOS.add(trackDrawDO);
            }
            this.insertBatch(trackDrawDOS);

            Wrapper<TrackDrawDO> wrapper2 = new EntityWrapper<>();
            wrapper.orderBy(true,"sort");
            Page<TrackDrawDO> trackDrawDOPage1 = this.selectPage(page, wrapper2);
            trackDrawDOPage1.getRecords().get(0).setHasDraw(hasDraw);
            trackDrawDOPage1.getRecords().get(0).setTotal(trackDrawDOPage1.getTotal());
            return trackDrawDOPage1;

        }
        trackDrawDOS.get(0).setHasDraw(hasDraw);
        trackDrawDOS.get(0).setTotal(trackDrawDOPage.getTotal());
        trackDrawDOPage.setRecords(trackDrawDOS);

        return trackDrawDOPage;
    }

}


